package com.runen.infinitemovement.tool;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.RequiresApi;

import com.runen.rxnetlibrary.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class ShareBitmapUtils {
    /**
     * 生成海报图片
     */
    public static Bitmap savePoster(Activity context, View layoutView) {
        //获取当前屏幕的大小
        int width = context.getWindow().getDecorView().getRootView().getWidth();
        int height = context.getWindow().getDecorView().getRootView().getHeight();
        //生成相同大小的图片（用来存储截屏后生成的bitmap对象）
        Bitmap temBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //找到当前页面的根布局（需要截屏的View）
        View view = layoutView;
        //view.getDrawingCache()==null时，需要重新测量view的宽高
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        //设置缓存
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        //从缓存中获取当前屏幕的图片
        temBitmap = view.getDrawingCache().copy(Bitmap.Config.ARGB_8888, false);
        //将截屏图片保存至本地
//        saveToLocal(temBitmap);
        //销毁当前屏幕图片的缓存
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(false);
        return temBitmap;
    }

    /**
     * 保存一张Bitmap图到本地
     */
    public static String saveToLocal(Context context, Bitmap bitmap) {
        String imagePath = "";
        if (Build.VERSION.SDK_INT >= 30) {
            saveImageToGallery(context, bitmap);
        } else {
            try {
                File appDir = new File(Environment.getExternalStorageDirectory(), "sharePoster");
                // 没有目录创建目录
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                Long mImageTime = System.currentTimeMillis();
                String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
                String SCREENSHOT_FILE_NAME_TEMPLATE = "wyyd_%s.png";//图片名称，以"wuyayundong_"+时间戳命名
                String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
                File file = new File(appDir, mImageFileName);

                FileOutputStream out;
                try {
                    out = new FileOutputStream(file);
                    if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                        out.flush();
                        out.close();
                        // 通知图库更新
                        Uri uri = Uri.fromFile(file);
                        Intent scannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                        context.sendBroadcast(scannerIntent);
                        imagePath = file.getPath();
                        ToastUtils.showLong("保存图片到相册成功");
                        Log.e("123456789", "saveToLocal: " + file.getPath());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return imagePath;
    }

    /**
     * android 11及以上保存图片到相册
     *
     * @param context
     * @param image
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    public static String saveImageToGallery(Context context, Bitmap image) {
        String imagePath = "";
        Long mImageTime = System.currentTimeMillis();
        String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
        String SCREENSHOT_FILE_NAME_TEMPLATE = "wyyd__%s.png";//图片名称，以"wuyayundong_"+时间戳命名
        String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);

        final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
                + File.separator + "sharePoster"); //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"dh"
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, mImageFileName);
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
        values.put(MediaStore.MediaColumns.IS_PENDING, 1);

        ContentResolver resolver = context.getContentResolver();

        final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            // First, write the actual data for our screenshot
            try (OutputStream out = resolver.openOutputStream(uri)) {
                if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    throw new IOException("Failed to compress");
                }
            }
            // Everything went well above, publish it!
            values.clear();
            values.put(MediaStore.MediaColumns.IS_PENDING, 0);
            values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
            resolver.update(uri, values, null, null);
            imagePath = Environment.DIRECTORY_PICTURES + File.separator + "sharePoster/" + mImageFileName;
            Log.e("123456789", "saveImageToGallery: " + imagePath);
            ToastUtils.showLong("保存图片到相册成功");
        } catch (IOException e) {
            resolver.delete(uri, null);
        }
        return imagePath;
    }
}
